<?php

namespace Ignus\View\Node;

use Ignus\View\Node;
use Ignus\View\Node\Text;
use Ignus\View\Compiler;
use Ignus\View\NodeInterface;
use Ignus\View\NodeOutputInterface;
use Ignus\View\Node\Expression\Constant;

class Module extends Node
{
    public function __construct(NodeInterface $body, Expression $parent = null, NodeInterface $blocks, NodeInterface $macros, NodeInterface $traits, $filename)
    {
        $nodes = array(
            'parent'    => $parent,
            'body'      => $body,
            'blocks'    => $blocks,
            'macros'    => $macros,
            'traits'    => $traits,
        );
        parent::__construct($nodes, array('filename' => $filename), 1);
    }

    public function compile(Compiler $compiler)
    {
        $this->compileTemplate($compiler);
    }

    protected function compileTemplate(Compiler $compiler)
    {
        $this->compileClassHeader($compiler);

        if (count($this->getNode('blocks')) || count($this->getNode('traits'))) {
            $this->compileConstructor($compiler);
        }

        $this->compileGetParent($compiler);

        $this->compileDisplayHeader($compiler);

        $this->compileDisplayBody($compiler);

        $this->compileDisplayFooter($compiler);

        $compiler->subcompile($this->getNode('blocks'));

        $this->compileMacros($compiler);

        $this->compileGetTemplateName($compiler);

        $this->compileIsTraitable($compiler);

        $this->compileClassFooter($compiler);
    }

    protected function compileGetParent(Compiler $compiler)
    {
        $compiler
            ->write("protected function doGetParent(array \$context)\n", "{\n")
            ->indent()
            ->write("return ");

        if (null === $this->getNode('parent')) {
            $compiler->raw("false");
        }
        else {
            if ($this->getNode('parent') instanceof Constant) {
                $compiler->subcompile($this->getNode('parent'));
            }
            else {
                $compiler
                    ->raw("\$this->env->resolveTemplate(")
                    ->subcompile($this->getNode('parent'))
                    ->raw(")");
            }
        }

        $compiler
            ->raw(";\n")
            ->outdent()
            ->write("}\n\n");
    }

    protected function compileDisplayBody(Compiler $compiler)
    {
        $compiler->write("\$context = array_merge(\$this->env->getGlobals(), \$context);\n\n");
        $compiler->subcompile($this->getNode('body'));

        if (null !== $this->getNode('parent')) {
            $compiler->write("\$this->getParent(\$context)->display(\$context, array_merge(\$this->blocks, \$blocks));\n");
        }
    }

    protected function compileClassHeader(Compiler $compiler)
    {
        $compiler
            ->write("<?php\n\n")
            // if the filename contains */, add a blank to avoid a PHP parse error
            ->write("/* ".str_replace('*/', '* /', $this->getAttribute('filename'))." */\n")
            ->write('class '.$compiler->getEnvironment()->getTemplateClass($this->getAttribute('filename')))
            ->raw(sprintf(" extends %s\n", $compiler->getEnvironment()->getBaseTemplateClass()))
            ->write("{\n")
            ->indent();
    }

    protected function compileConstructor(Compiler $compiler)
    {
        $compiler
            ->write("public function __construct(\\Ignus\\View\\Environment \$env)\n", "{\n")
            ->indent()
            ->write("parent::__construct(\$env);\n\n");

        $countTraits = count($this->getNode('traits'));
        if ($countTraits) {
            // traits
            foreach ($this->getNode('traits') as $i => $trait) {

                /** @var \Ignus\View\Node $trait */
                $this->compileLoadTemplate($compiler, $trait->getNode('template'), sprintf('$_trait_%s', $i));

                $compiler
                    ->addDebugInfo($trait->getNode('template'))
                    ->write(sprintf("if (!\$_trait_%s->isTraitable()) {\n", $i))
                    ->indent()
                    ->write('throw new \Ignus\View\Error\Runtime(\'Template "\'.')
                    ->subcompile($trait->getNode('template'))
                    ->raw(".'\" cannot be used as a trait.');\n")
                    ->outdent()
                    ->write("}\n")
                    ->write(sprintf("\$_trait_%s_blocks = \$_trait_%s->getBlocks();\n\n", $i, $i));

                foreach ($trait->getNode('targets') as $key => $value) {
                    $compiler
                        ->write(sprintf("\$_trait_%s_blocks[", $i))
                        ->subcompile($value)
                        ->raw(sprintf("] = \$_trait_%s_blocks[", $i))
                        ->string($key)
                        ->raw(sprintf("]; unset(\$_trait_%s_blocks[", $i))
                        ->string($key)
                        ->raw("]);\n\n");
                }
            }

            $compiler
                ->write("\$this->traits = array_merge(\n")
                ->indent();

            for ($i = 0; $i < $countTraits; $i++) {
                $compiler->write(sprintf("\$_trait_%s_blocks".($i == $countTraits - 1 ? '' : ',')."\n", $i));
            }

            $compiler
                ->outdent()
                ->write(");\n\n")
                ->write("\$this->blocks = array_merge(\n")
                ->indent()
                ->write("\$this->traits,\n")
                ->write("array(\n");
        }
        else {
            $compiler->write("\$this->blocks = array(\n");
        }

        // blocks
        $compiler->indent();

        foreach ($this->getNode('blocks') as $name => $node) {
            $compiler->write(sprintf("'%s' => array(\$this, 'block_%s'),\n", $name, $name));
        }

        if ($countTraits) {
            $compiler->outdent()->write(")\n");
        }

        $compiler
            ->outdent()
            ->write(");\n")
            ->outdent()
            ->write("}\n\n");
    }

    protected function compileDisplayHeader(Compiler $compiler)
    {
        $compiler
            ->write("protected function doDisplay(array \$context, array \$blocks = array())\n", "{\n")
            ->indent();
    }

    protected function compileDisplayFooter(Compiler $compiler)
    {
        $compiler
            ->outdent()
            ->write("}\n\n");
    }

    protected function compileClassFooter(Compiler $compiler)
    {
        $compiler
            ->outdent()
            ->write("}\n");
    }

    protected function compileMacros(Compiler $compiler)
    {
        $compiler->subcompile($this->getNode('macros'));
    }

    protected function compileGetTemplateName(Compiler $compiler)
    {
        $compiler
            ->write("public function getTemplateName()\n", "{\n")
            ->indent()
            ->write('return ')
            ->repr($this->getAttribute('filename'))
            ->raw(";\n")
            ->outdent()
            ->write("}\n\n");
    }

    protected function compileIsTraitable(Compiler $compiler)
    {
        // A template can be used as a trait if:
        //   * it has no parent
        //   * it has no macros
        //   * it has no body
        //
        // Put another way, a template can be used as a trait if it
        // only contains blocks and use statements.
        $traitable = null === $this->getNode('parent') && 0 === count($this->getNode('macros'));
        if ($traitable) {
            if (!count($nodes = $this->getNode('body'))) {
                $nodes = new Node(array($this->getNode('body')));
            }

            foreach ($nodes as $node) {
                /** @var \Ignus\View\Node $node */
                if (!count($node)) {
                    continue;
                }

                if ($node instanceof Text && ctype_space($node->getAttribute('data'))) {
                    continue;
                }

                if ($node instanceof BlockReference) {
                    continue;
                }

                $traitable = false;
                break;
            }
        }

        $compiler
            ->write("public function isTraitable()\n", "{\n")
            ->indent()
            ->write(sprintf("return %s;\n", $traitable ? 'true' : 'false'))
            ->outdent()
            ->write("}\n");
    }

    public function compileLoadTemplate(Compiler $compiler, $node, $var)
    {
        if ($node instanceof Constant) {
            $compiler
                ->write(sprintf('%s = $this->env->loadTemplate(', $var))
                ->subcompile($node)
                ->raw(");\n");
        }
        else {
            $compiler
                ->write(sprintf('%s = ', $var))
                ->subcompile($node)
                ->raw(";\n")
                ->write(sprintf('if (!%s', $var))
                ->raw(' instanceof \Ignus\View\Template) {' . "\n")
                ->indent()
                ->write(sprintf("%s = \$this->env->loadTemplate(%s);\n", $var, $var))
                ->outdent()
                ->write("}\n");
        }
    }
}
